package com.kgc.provider;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.kgc.api.buylimit.TradeOrderApi;

import com.kgc.bean.*;
import com.kgc.mapper.DiscountUserTrickMapper;
import com.kgc.mapper.OrderInfoMapper;
import com.kgc.mapper.OrderItemMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import javax.jms.Destination;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author：周申宇 <p>
 * @Date:2021/6/6 15:13
 * <p>
 * @Decription:  电子文档操作服务提供者
 */
@Service //  所在包alibaba ，实现服务的注册为提供者
@Slf4j
public class TradeOrderProvider implements TradeOrderApi {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private DiscountUserTrickMapper discountUserTrickMapper;

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    /**
     * @Author: zhouyu
     * @Param: [user, goodsItemVo, num, tradeOrderNo]
     * @Return: void
     * @Description: 订单封装，订单详情封装 消息队列发送数据
     */
    @Override
    public void createTradeOrder(User user, GoodsItemVo goodsItemVo,Integer num, String tradeOrderNo) {

        // 收到下单请求，参数校验，封装实体，发送消息队列
        log.info("-----------------------");



        // 订单详情封装
        OrderItem orderItem =OrderItem
                                .builder()
                                .orderId(tradeOrderNo)
                                .goodsId(goodsItemVo.getGoodsId())
                                .title(goodsItemVo.getGoodsName())
                                .prePrice(goodsItemVo.getGoodsPrice())
                                .num(num)
                                .totalPrice(num * goodsItemVo.getGoodsPrice())
                                .build();

        // 把用户收货地址封装成json数据
        UserReviverInfo userReviverInfo = UserReviverInfo
                .builder()
                .id(20)
                .userId(1001)
                .receiverName("周小生")
                .receiverPhone("167890001")
                .receiverState("江苏")
                .receiverCity("南京")
                .receiverDistrict("江宁")
                .receiverAddress("金科院")
                .build();
        // 转成json数据
        String userRevierInfo = JSON.toJSONString(userReviverInfo);

        OrderInfo orderInfo = null;
        // 订单封装
        try {
            orderInfo = OrderInfo
                    .builder()
                    .userId(user.getUserId())
                    .orderId(tradeOrderNo)
                    .orderPayment(orderItem.getTotalPrice())
                    .orderLogisticsInfo(userRevierInfo)
                    .orderCreateTime(df.parse(df.format(new Date())))
                    // 未付款
                    .orderStatus(1)
                    .orderPaymentType(0)
                    .build();
        }catch (Exception e ){
            log.info("异常{}",e.getMessage());
            e.printStackTrace();
        }

        // 把数据存放到hasmap中
        Map<String,Object> map = new HashMap<>();
        map.put("orderItem",orderItem);
        map.put("orderInfo",orderInfo);

        String mapStr = JSON.toJSONString(map);

        // 创建一个目标消息队列（消息容器）
        Destination destination = new ActiveMQQueue("buy-limit-trade-order");
        log.info("消息队列：buy-limit-trade-order 正在发消息");
        // 向目标队列发送消息
        jmsMessagingTemplate.convertAndSend(destination,mapStr);
    }


    /**
     * @Author: zhouyu
     * @Param: [orderInfo, orderItem]
     * @Return: java.lang.String
     * @Description: 把订单数据插入数据库
     */
    public String insertTradeOrderFromQueue(OrderInfo orderInfo,OrderItem orderItem){

        //
        Integer statue1 = orderInfoMapper.insertOrderInfo(orderInfo);
        //
        Integer statue2 = orderItemMapper.addOrderItem(orderItem);

        if (statue1 ==0){
            return "订单数据插入失败";
        }
        if (statue2 == 0){
            return "订单详情数据插入失败";
        }
        return "订单生成成功";
    }

    @Override
    public OrderInfo getOrderInfoByOrderInfoId(String orderInfoId) {
        return orderInfoMapper.selectOrderInfoByOrderInfoId(orderInfoId);
    }

    @Override
    public Integer updateOrderInfoByOrderInfoId(String orderInfoId) {
        // 不是抢购商品需要判断是否使用优惠卷
        OrderInfo orderInfo = orderInfoMapper.selectOrderInfoByOrderInfoId(orderInfoId);
        // 如果不是抢购商品，支付成功修改优惠卷的使用状态
        if(null != orderInfo.getDiscountTrckId()){
            discountUserTrickMapper.updateTrickByUserIdAndDiscountId(orderInfo.getUserId(),orderInfo.getDiscountTrckId());
        }

        // 修改订单状态
        return orderInfoMapper.updateOrderInfoByOrderInfoId(orderInfoId);
    }

    @Override
    public String insertOrderInfoByOrderInfo(OrderInfo orderInfo) {
        Integer statue1 = orderInfoMapper.insertOrderInfo(orderInfo);
        if (statue1 ==0){
            return "订单数据插入失败";
        }
        return "订单生成成功";
    }

    @Override
    public String insertOrderItemByOrderItem(List<OrderItem> orderItems) {

        for (int i = 0;i< orderItems.size();i++){
            orderItemMapper.addOrderItem(orderItems.get(i));
        }
        return "商品详情生成成功";
    }

    @Override
    public Boolean updateOrderInfoByLoggistics(OrderInfo orderInfo) {

        return orderInfoMapper.updateOrderInfo(orderInfo) > 0;
    }


}
